<template>
    <Modal :value="show" :width="640" @on-visible-change="setVisibility" title="电话解决工单">
        <Form :label-width="100" v-if="ticket">
            <Form-item class="margin-bottom-10" label="工单编号：">{{ticket.ticket_sn}}</Form-item>

            <Form-item class="margin-bottom-10" label="详细地址：">{{concatLocation(ticket.home_info)}}</Form-item>
            <Form-item class="margin-bottom-20" label="说明：">
                <Input :rows="1" disabled style="width: 340px" type="textarea" v-model="description"/>
            </Form-item>

            <Alert class="margin-bottom-20">请填写完整的故障分类和解决方案，否则不会写入记录</Alert>
            <Collapse>
                <Panel :key="index" v-for="(item, index) in ticketData.ticket_devices">
                    房间 - {{item.room_name}}
                    <div slot="content">
                        <Row :gutter="20">
                            <i-col span="12">设备: {{item.device_type | deviceType}}</i-col>
                            <i-col span="12">设备SN: {{item.sn || '-'}}</i-col>
                            <i-col span="12">故障描述: {{ticket.ticket_devices[index].description}}</i-col>
                            <i-col span="12">故障时间: {{ticket.ticket_devices[index].fault_time | date('YYYY-MM-DD HH:ss')}}</i-col>
                            <i-col span="12">建议处理方案: {{ticket.ticket_devices[index].note}}</i-col>
                        </Row>

                        <Row class="as-edit-row" v-if="faults[ticketData.ticket_devices[index]['device_type']]">
                            <i-col span="12">
                                <span class="as-edit-key">一级故障:</span>
                                <Select
                                    @on-change="ticketData.ticket_devices[index].fault_id = ''"
                                    style="width: 180px"
                                    v-model="ticketData.ticket_devices[index].first_fault_id"
                                >
                                    <Option
                                        :key="firstFault.id"
                                        :value="firstFault.id"
                                        v-for="firstFault in faults[ticketData.ticket_devices[index]['device_type']].firstFaults"
                                    >{{firstFault.name}}</Option>
                                </Select>
                            </i-col>
                            <i-col span="12">
                                <span class="as-edit-key">二级故障:</span>
                                <Select
                                    @on-change="(id) => fetchSolutions(id, index)"
                                    style="width: 180px"
                                    v-model="ticketData.ticket_devices[index].fault_id"
                                >
                                    <Option
                                        :key="fault.id"
                                        :value="fault.id"
                                        v-for="fault in faults[ticketData.ticket_devices[index]['device_type']].faults[ticketData.ticket_devices[index].first_fault_id]"
                                        v-if="ticketData.ticket_devices[index].first_fault_id"
                                    >{{fault.name}}</Option>
                                </Select>
                            </i-col>
                        </Row>
                        <Row class="as-edit-row" v-if="ticketData.ticket_devices[index].fault_id">
                            <i-col span="24">
                                <span class="as-edit-key">解决方案:</span>
                                <Select style="width: 180px" v-model="ticketData.ticket_devices[index].solution_id">
                                    <Option
                                        :key="solution.id"
                                        :value="solution.id"
                                        v-for="solution in solutions[ticketData.ticket_devices[index].fault_id]"
                                    >{{solution.name}}</Option>
                                </Select>
                            </i-col>
                        </Row>
                    </div>
                </Panel>
            </Collapse>
        </Form>

        <div slot="footer">
            <Button @click="setVisibility(false)" type="text">取消</Button>
            <Button :loading="loading" @click="handleSubmit" type="primary">保存</Button>
        </div>
    </Modal>
</template>

<script>
import cloneDeep from 'lodash/cloneDeep'
import { http, api } from '@/libs/http'
import dataCenter from '@/libs/dataCenter'
import util from '@/libs/util'

export default {
  name: 'mobile-solution',
  props: {
    show: Boolean,
    ticket: Object
  },
  data () {
    return {
      loading: false,
      description: '电话解决',
      ticketData: {},
      faults: {},
      solutions: {}
    }
  },
  watch: {
    show (n) {
      if (!n) {
        this.ticketData = {}
        setTimeout(() => {
          this.$emit('update:ticket', null)
        }, 500)
      } else {
        this.ticketData = cloneDeep(this.ticket)
        this.initFaults()
      }
    }
  },
  methods: {
    concatLocation: util.concatAddress,
    setVisibility (val) {
      this.$emit('update:show', val)
    },
    async initFaults () {
      const deviceTypes = this.ticketData.ticket_devices.reduce((ids, item) => {
        return ids.includes(item.device_type) ? ids : ids.concat([item.device_type])
      }, [])
      for (let type of deviceTypes) {
        const result = await dataCenter.fetchFaults(this, type)
        this.$set(this.faults, type, result)
      }
    },
    async fetchSolutions (id, index) {
      this.$set(this.ticketData.ticket_devices[index], 'solution_id', '')
      const result = await dataCenter.fetchSolutions(this, id)
      this.$set(this.solutions, id, result)
    },
    generateFromData () {
      const { ticket_devices } = this.ticketData
      const result = { description: this.description }
      const data = []
      ticket_devices.forEach(item => {
        const { room_id, device_id, device_type, fault_id, solution_id } = item
        if (fault_id && solution_id) {
          const solution_name = this.solutions[fault_id].find(item => item.id === solution_id).name
          data.push({ room_id, device_id, device_type, fault_id, solution_id, solution_name })
        }
      })
      if (data.length > 0) result.ticket_devices = data
      return result
    },
    async handleSubmit () {
      try {
        this.loading = true
        const data = this.generateFromData()
        // console.log(data);
        const res = await http.fetch(this, api.ticket_close, [this.ticket.id], data)
        if (res) {
          this.$Message.success('操作成功')
          this.$emit('refresh')
          this.setVisibility(false)
        }
      } catch (err) {
        console.log(err)
      } finally {
        this.loading = false
      }
    }
  }
}
</script>